<template>
  <div>
    <div class="i-layout-page-header">
      <div class="i-layout-page-header">
        <span class="ivu-page-header-title">{{ $route.meta.title }}</span>
      </div>
    </div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Form
        ref="formValidate"
        :model="formValidate"
        :label-width="labelWidth"
        :label-position="labelPosition"
        @submit.native.prevent
      >
        <Row v-if="false" type="flex" :gutter="24">
          <!--          <Col v-bind="grid">-->
          <!--            <FormItem label="状态：" label-for="status">-->
          <!--              <Select v-model="formValidate.status" placeholder="请选择" @on-change="userSearchs" clearable>-->
          <!--                <Option value="1">显示</Option>-->
          <!--                <Option value="0">不显示</Option>-->
          <!--              </Select>-->
          <!--            </FormItem>-->
          <!--          </Col>-->
          <Col v-bind="grid">
            <FormItem label="角色名称：" label-for="name">
              <Input
                enter-button
                placeholder="请输入角色名称"
                v-model="formValidate.name"
              />
            </FormItem>
          </Col>
          <Col class="ivu-text-right userFrom">
            <FormItem>
              <Button type="primary" icon="ios-search" label="default" class="mr15" @click="userSearchs">查询</Button>
              <Button class="ResetSearch" @click="reset('userFrom')">重置</Button>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex">
          <Col v-bind="grid">
            <Button v-auth="['setting-system_role-add']" type="primary" icon="md-add" @click="add('添加')">新建角色
            </Button>
          </Col>
        </Row>
      </Form>
      <Table
        :columns="columns1"
        :data="tableList"
        ref="table"
        class="mt25"
        :loading="loading"
        highlight-row
        no-userFrom-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
      >
        <template slot-scope="{ row, index }" slot="is_shows">
          <i-switch
            v-model="row.status"
            :value="row.status"
            :true-value="1"
            :false-value="0"
            @on-change="onchangeIsShow(row)"
            size="large"
          >
            <span slot="open">显示</span>
            <span slot="close">隐藏</span>
          </i-switch>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <a @click="edit(row, '编辑')">编辑</a>
          <!--          <Divider type="vertical" />-->
          <!--          <a @click="del(row, '删除'+row.name, index)">删除</a>-->
        </template>
      </Table>
      <!--      <div class="acea-row row-right page">-->
      <!--        <Page-->
      <!--          :total="total"-->
      <!--          :current="formValidate.current"-->
      <!--          show-elevator-->
      <!--          show-total-->
      <!--          @on-change="pageChange"-->
      <!--          :page-size="formValidate.limit"-->
      <!--        />-->
      <!--      </div>-->
    </Card>
    <!-- 新增编辑-->
    <Modal
      v-model="modals"
      @on-cancel="onCancel"
      scrollable
      footer-hide
      closable
      :title="`${modelTit}角色`"
      :mask-closable="false"
      width="85%"
    >
      <Form
        ref="formInline"
        :model="formInline"
        :rules="ruleValidate"
        :label-width="100"
        :label-position="labelPosition2"
        @submit.native.prevent
      >
        <FormItem label="角色名称：" label-for="name" prop="name">
          <Input placeholder="请输入角色名称" v-model="formInline.name" />
        </FormItem>
        <FormItem label="角色描述：" label-for="shuoming" prop="shuoming">
          <Input
            v-model="formInline.shuoming"
            value=""
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入角色描述"
          ></Input>
        </FormItem>
        <FormItem label="是否开启：" prop="status">
          <RadioGroup v-model="formInline.status">
            <Radio :label="1">开启</Radio>
            <Radio :label="0">关闭</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="角色类型：" prop="type">
          <RadioGroup v-model="formInline.type">
            <Radio :label="1">管理员角色</Radio>
            <Radio :label="2">其他</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="分配权限：">
          <div class="trees-coadd">
            <div class="scollhide">
              <div class="iconlist">
                <Tree :data="menusList" show-checkbox ref="tree"></Tree>
              </div>
            </div>
          </div>
        </FormItem>
        <FormItem label="分配用户：">
          <Button type="primary" icon="md-add" class="ResetSearch" @click="selectRoleAdminUser()">选择用户</Button>
          <Table
            :columns="columnsRoleUser"
            :data="roleUserList"
            ref="table"
            class="mt25"
            :loading="loading"
            highlight-row
            no-userFrom-text="暂无数据"
            no-filtered-userFrom-text="暂无筛选结果"
          >
            <template slot-scope="{ row, index }" slot="action">
              <a @click="roleUserDel(row,index)">删除</a>
            </template>
          </Table>
        </FormItem>
        <Spin size="large" fix v-if="spinShow"></Spin>
        <Button type="primary" size="large" long @click="handleSubmit('formInline')">提交</Button>
      </Form>
    </Modal>
    <!--选择后台用户-->
    <Modal
      v-model="modalsRoleUser"
      title="后台用户列表"
      footerHide
      class="paymentFooter"
      width="900"
      @on-cancel="cancelModalsRoleUser"
    >
      <role-admin-list ref="roleAdminList" @ischeckbox="true" @getRoleAdminId="getRoleAdminId"></role-admin-list>
    </Modal>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { roleListApi, roleSetStatusApi, menusListApi, roleCreatApi, roleInfoApi, roleUpdateApi } from "@/api/setting";
import roleAdminList from "@/components/roleAdminList/index.vue";
import { selectSystUserDetailApi, selectSystUserhquanxianDetailApi, systemRoleListApi, selectSystUserApi } from "@/api/systemAdmin";
import { getTable } from "@/api/systemMenus";

export default {
  name: "systemrRole",
  components: { roleAdminList },
  data() {
    return {
      spinShow: false,
      modals: false,
      modalsRoleUser: false,
      total: 0,
      grid: {
        xl: 7,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24
      },
      loading: false,
      formValidate: {
        name: ""
        // current: 1,
        // size: 20
      },
      columns1: [
        {
          title: "ID",
          key: "id",
          width: 80
        },
        {
          title: "角色名称",
          key: "name",
          minWidth: 120
        },
        {
          title: "角色描述",
          key: "shuoming",
          minWidth: 120
        },
        {
          title: "分配用户",
          key: "operateIp",
          minWidth: 120
        },
        {
          title: "分配时间",
          key: "operateTime",
          minWidth: 120
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          minWidth: 120
        }
      ],
      columnsRoleUser: [
        {
          title: "用户ID",
          key: "id"
        },
        {
          title: "公司名称",
          key: "sqmc"
        },
        {
          title: "姓名",
          key: "name"
        },
        {
          title: "联系电话",
          key: "phone"
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          minWidth: 120
        }
      ],
      tableList: [],
      roleUserList: [],
      formInline: {
        "asysAcllistid": "",
        "id": 0,
        "name": "",
        "operateIp": "",
        "operateTime": "",
        "remark": "",
        "shuoming": "",
        "status": 1,
        "sysUserid": "",
        "type": 2
      },
      menusList: [],
      modelTit: "",
      ruleValidate: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        shuoming: [{ required: true, message: "请输入角色说明", trigger: "blur" }]
        // status: [{ required: true, type: 'number', message: '请选择是否开启', trigger: 'change' }],
        // checked_menus: [
        //     { required: true, validator: validateStatus, trigger: 'change' }
        // ]
      }
    };
  },
  computed: {
    ...mapState("media", ["isMobile"]),
    labelWidth() {
      return this.isMobile ? undefined : 75;
    },
    labelPosition() {
      return this.isMobile ? "top" : "left";
    },
    labelPosition2() {
      return this.isMobile ? "top" : "right";
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // 添加
    add(name) {
      this.formInline.id = 0;
      this.modelTit = name;
      this.modals = true;
      this.getmenusList();
    },
    // 删除
    del(row, tit, num) {
      let delfromData = {
        title: tit,
        num: num,
        url: `setting/role/${row.id}`,
        method: "DELETE",
        ids: ""
      };
      this.$modalSure(delfromData)
        .then((res) => {
          this.$Message.success(res.msg);
          this.tableList.splice(num, 1);
        })
        .catch((res) => {
          this.$Message.error(res.msg);
        });
    },
    //删除角色用户（本地变量）
    roleUserDel(row, index) {
      this.roleUserList.splice(index, 1);
      this.$forceUpdate();
    },
    // 修改是否显示
    onchangeIsShow(row) {
      let data = {
        id: row.id,
        status: row.status
      };
      roleSetStatusApi(data)
        .then(async (res) => {
          this.$Message.success(res.msg);
        })
        .catch((res) => {
          this.$Message.error(res.msg);
        });
    },
    // 列表
    getList() {
      let params = {
        // current: this.formValidate.current,
        // size: this.formValidate.size
      };
      if (this.formValidate.name != "") {
        params.name = this.formValidate.name;
      }
      this.loading = true;
      systemRoleListApi(params)
        .then(async (res) => {
          this.tableList = res.data;
          // this.total = res.data.count;
          this.loading = false;
        })
        .catch((res) => {
          this.loading = false;
          this.$Message.error("获取失败");
        });
    },
    pageChange(index) {
      this.formValidate.current = index;
      this.getList();
    },
    // 表格搜索
    userSearchs() {
      this.formValidate.current = 1;
      this.getList();
    },
    // 重置
    reset(name) {
      this.formValidate = {
        name: "",
        current: 1,
        size: 20
      };
      this.getList();
    },
    // 编辑
    edit(row, name) {
      this.modals = true;
      this.modelTit = name;
      this.formInline.id = row.id;
      this.formInline = row;
      // this.rows = row;
      // this.getmenusList();
      this.getSelectSystUserhquanxianDetails(row);
      this.getSelectSystUser(row);
    },
    // 菜单列表
    getmenusList() {
      this.spinShow = true;
      getTable()
        .then(async (res) => {
          let data = res.data;
          this.menusList = data;
          // this.menusList = data.menus;
          this.menusList.map((item, index) => {
            item.pid = item.aclModuleId;
            item.title = item.name;

            let children = item.listAsysAcl;
            children.map((subItem, subIndex) => {
              subItem.pid = subItem.aclModuleId;
              subItem.title = subItem.name;

              let thirdChildren = subItem.listAsysAcl;
              thirdChildren.map((thirdItem, thirdIndex) => {
                thirdItem.pid = thirdItem.aclModuleId;
                thirdItem.title = thirdItem.name;
                thirdItem.children = thirdItem.listAsysAcl;
              });
              subItem.children = thirdChildren;
            });
            item.children = children;

            // if (item.title === "首页") {
            //   item.checked = true;
            //   item.disableCheckbox = true;
            //   if (item.children.length) {
            //     item.children.map((v) => {
            //       v.checked = true;
            //       v.disableCheckbox = true;
            //     });
            //   }
            // }
            item.expand = false;
          });
          this.spinShow = false;
        })
        .catch((res) => {
          this.spinShow = false;
          this.$Message.error(res.msg);
        });
    },
    // 分配的权限
    getSelectSystUserhquanxianDetails(row) {
      this.spinShow = true;
      selectSystUserhquanxianDetailApi({ roleid: row.id })
        .then(async (res) => {
          let data = res.data;
          // this.menusList = data;
          // this.formInline = data.role || this.formInline;
          // this.formInline.checked_menus = this.formInline.rules;
          this.tidyRes(data);
          this.spinShow = false;
        })
        .catch((res) => {
          this.spinShow = false;
          this.$Message.error(res.msg);
        });
    },
    // 角色管理的用户
    getSelectSystUser(row) {
      this.spinShow = true;
      selectSystUserApi({ roleid: row.id })
        .then(async (res) => {
          let data = res.data;
          this.roleUserList = data;
          // this.formInline = data.role || this.formInline;
          // this.formInline.checked_menus = this.formInline.rules;
        })
        .catch((res) => {
          this.spinShow = false;
          this.$Message.error(res.msg);
        });
    },
    tidyRes(menus) {
      let data = [];
      menus.map((menu) => {
        if (menu.title === "主页") {
          menu.checked = true;
          menu.disableCheckbox = true;
          if (menu.children.length) {
            menu.children.map((v) => {
              v.checked = true;
              v.disableCheckbox = true;
            });
          }
          data.push(menu);
        } else {
          data.push(this.initMenu(menu));
        }
      });
      this.$set(this, "menusList", data);
    },
    initMenu(menu) {
      let data = {},
        checkMenus = "," + this.formInline.checked_menus + ",";
      data.title = menu.title;
      data.id = menu.id;
      if (menu.children && menu.children.length > 0) {
        data.children = [];
        menu.children.map((child) => {
          data.children.push(this.initMenu(child));
        });
      } else {
        data.checked = checkMenus.indexOf(String("," + data.id + ",")) !== -1;
        data.expand = !data.checked;
      }
      return data;
    },
    // 提交
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let asysAcllistid = [];
          this.$refs.tree.getCheckedAndIndeterminateNodes().map((node) => {
            asysAcllistid.push(node.id);
          });
          if (asysAcllistid.length === 0) return this.$Message.warning("请至少选择一个权限");

          let sysUserid = [];
          this.roleUserList.map((item) => {
            sysUserid.push(item.id);
          });
          if (sysUserid.length === 0) return this.$Message.warning("请选择需要分配权限的用户");

          this.formInline.asysAcllistid = asysAcllistid.join(",");
          this.formInline.sysUserid = sysUserid.join(",");
          if (this.formInline.id != 0){
            roleUpdateApi(this.formInline)
              .then(async (res) => {
                this.$Message.success("操作成功");
                this.modals = false;
                this.getList();
                this.$refs[name].resetFields();
                this.formInline.asysAcllistid = "";
                this.formInline.sysUserid = "";
              })
              .catch((res) => {
                this.$Message.error(res.msg);
              });
          } else {
            roleCreatApi(this.formInline)
              .then(async (res) => {
                this.$Message.success("操作成功");
                this.modals = false;
                this.getList();
                this.$refs[name].resetFields();
                this.formInline.asysAcllistid = "";
                this.formInline.sysUserid = "";
              })
              .catch((res) => {
                this.$Message.error(res.msg);
              });
          }
        } else {
          return false;
        }
      });
    },
    onCancel() {
      this.$refs["formInline"].resetFields();
      this.formInline.checked_menus = [];
      this.roleUserList = [];
    },
    // 选择用户
    selectRoleAdminUser() {
      this.modalsRoleUser = true;
      this.$refs.roleAdminList.formValidate.is_presale = 0;
      this.$refs.roleAdminList.getList();
      // this.$refs.roleAdminList.goodsCategory();
    },
    // 角色用户
    getRoleAdminId(row) {
      this.modal_loading = false;
      this.modalsRoleUser = false;
      this.roleUserList = row;
    },
    cancelModalsRoleUser() {
      this.modalsRoleUser = false;
    }
  }
};
</script>

<style scoped lang="stylus">
.trees-coadd
  width: 100%;
  height: 385px;

  .scollhide
    width: 100%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;

// margin-left: 18px;
.scollhide::-webkit-scrollbar {
  display: none;
}
</style>
